package org.chen.web.aop;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.chen.enums.ApiResultEnum;
import org.chen.model.response.ApiResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.validation.ConstraintViolationException;

/**
 * @Author: 陈亮
 * @Date: 2019/3/24 19:06
 */
@Slf4j
@ControllerAdvice
@ResponseBody
public class ExceptionAdvice {

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({HttpMessageNotReadableException.class, MissingServletRequestParameterException.class, BindException.class,
            ServletRequestBindingException.class, MethodArgumentNotValidException.class, ConstraintViolationException.class})
    public ApiResult handleHttpMessageNotReadableException(Exception e) {
        log.error("参数解析失败", e);
        if (e instanceof BindException) {
            return new ApiResult(ApiResultEnum.BAD_REQUEST.getCode(), ((BindException) e).getAllErrors().get(0).getDefaultMessage());
        }
        return new ApiResult(ApiResultEnum.BAD_REQUEST.getCode(), e.getMessage());
    }

    /**
     * 405 - Method Not Allowed
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ApiResult handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        return new ApiResult(ApiResultEnum.METHOD_NOT_ALLOWED.getCode(), ApiResultEnum.METHOD_NOT_ALLOWED.getMsg());
    }

    /**
     * shiro权限异常处理
     *
     * @return
     */
    @ExceptionHandler({UnauthorizedException.class, AuthorizationException.class})
    public ApiResult unauthorizedException(Exception e) {
        return new ApiResult(ApiResultEnum.NO_ACCESS_PERMISSION.getCode(), ApiResultEnum.NO_ACCESS_PERMISSION.getMsg());
    }

    /**
     * 500
     *
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public ApiResult handleException(Exception e) {
        e.printStackTrace();
        log.error("服务运行异常", e);
        return new ApiResult(ApiResultEnum.SYSTEM_ERR.getCode(), ApiResultEnum.SYSTEM_ERR.getMsg());
    }
}
